<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue';

import {
  Delete,
  FullScreen,
  OfficeBuilding,
  Search,
  User,
  View,
} from '@element-plus/icons-vue';
import { ElMessage, ElTable, ElTree } from 'element-plus';

// 类型定义
interface User {
  id: number | string;
  name: string;
  avatar?: string;
  department: string;
  position: string;
  email: string;
  phone: string;
  status: 'active' | 'inactive';
}

interface Department {
  id: number | string;
  label: string;
  children?: Department[];
  userCount?: number;
}

// Props
interface Props {
  modelValue: boolean;
  title?: string;
  defaultSelected?: User[];
}

const props = withDefaults(defineProps<Props>(), {
  title: '选择用户',
  defaultSelected: () => [],
});

// Emits
const emit = defineEmits<{
  confirm: [users: User[]];
  'update:modelValue': [value: boolean];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});

const isFullscreen = ref(false);
const searchKeyword = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();
const tableRef = ref<InstanceType<typeof ElTree>>();
const loading = ref(false);
const showSelectedDrawer = ref(false);
const selectedDrawerUsers = ref<(number | string)[]>([]); // 在抽屉中选中的用户ID

// 其他数据...
const departmentTree = ref<Department[]>([
  /* 部门数据 */
]);
const userList = ref<User[]>([]);
const selectedUsers = ref<User[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalUsers = ref(0);

// 计算属性
const dialogWidth = computed(() => (isFullscreen.value ? '100%' : '60%')); // 稍微调宽以容纳新按钮
const fullscreenClass = computed(() =>
  isFullscreen.value ? 'fullscreen-dialog' : '',
);
const tableHeight = computed(() =>
  isFullscreen.value ? 'calc(100vh - 280px)' : '400',
);

const treeProps = {
  children: 'children',
  label: 'label',
};

// 方法
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
  nextTick(() => {
    if (tableRef.value) {
      tableRef.value.doLayout();
    }
  });
};

const handleSearch = () => {
  if (treeRef.value) {
    treeRef.value.filter(searchKeyword.value);
  }
  loadUserList();
};

const filterNode = (value: string, data: Department) => {
  if (!value) return true;
  return data.label.includes(value);
};

const handleNodeClick = (data: Department) => {
  currentPage.value = 1;
  loadUserList();
};

const loadUserList = async () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    userList.value = Array.from({ length: pageSize.value }, (_, index) => {
      const id = (currentPage.value - 1) * pageSize.value + index + 1;
      return {
        id,
        name: `用户${id}`,
        department: '技术部',
        position: '工程师',
        email: `user${id}@company.com`,
        phone: `138${String(id).padStart(8, '0')}`,
        status: 'active',
      };
    });
    totalUsers.value = 125;
    loading.value = false;
  }, 500);
};

const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection;
};

const clearSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
  selectedUsers.value = [];
  selectedDrawerUsers.value = [];
};

// 移除单个用户
const removeUser = (userId: number | string) => {
  // 从选中列表中移除
  selectedUsers.value = selectedUsers.value.filter(
    (user) => user.id !== userId,
  );

  // 从抽屉选择中移除
  selectedDrawerUsers.value = selectedDrawerUsers.value.filter(
    (id) => id !== userId,
  );

  // 更新表格的选择状态
  nextTick(() => {
    if (tableRef.value) {
      const row = userList.value.find((user) => user.id === userId);
      if (row) {
        tableRef.value.toggleRowSelection(row, false);
      }
    }
  });
};

// 移除抽屉中选中的用户
const removeSelectedFromDrawer = () => {
  selectedDrawerUsers.value.forEach((userId) => {
    removeUser(userId);
  });
  selectedDrawerUsers.value = [];
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  loadUserList();
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  loadUserList();
};

const handleClose = () => {
  dialogVisible.value = false;
  isFullscreen.value = false;
  searchKeyword.value = '';
  selectedUsers.value = [];
  selectedDrawerUsers.value = [];
  showSelectedDrawer.value = false;
};

const handleConfirm = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个用户');
    return;
  }
  emit('confirm', selectedUsers.value);
  handleClose();
};

// 监听抽屉显示状态，重置选择
watch(showSelectedDrawer, (newVal) => {
  if (!newVal) {
    selectedDrawerUsers.value = [];
  }
});

// 监听选中用户变化
watch(selectedUsers, (newVal) => {
  // 如果抽屉打开且选中用户为空，清空抽屉选择
  if (showSelectedDrawer.value && newVal.length === 0) {
    selectedDrawerUsers.value = [];
  }
});

// 初始化
watch(dialogVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (treeRef.value) {
        const firstNode = departmentTree.value[0];
        if (firstNode) {
          treeRef.value.setCurrentKey(firstNode.id);
        }
      }
      loadUserList();

      nextTick(() => {
        if (tableRef.value && props.defaultSelected.length > 0) {
          props.defaultSelected.forEach((user) => {
            const row = userList.value.find((u) => u.id === user.id);
            if (row) {
              tableRef.value.toggleRowSelection(row, true);
            }
          });
        }
      });
    });
  }
});

onMounted(() => {
  // 初始化部门数据
  departmentTree.value = [
    {
      id: 1,
      label: '总公司',
      userCount: 45,
      children: [
        {
          id: 2,
          label: '技术部',
          userCount: 20,
          children: [
            { id: 3, label: '前端组', userCount: 8 },
            { id: 4, label: '后端组', userCount: 12 },
          ],
        },
        {
          id: 5,
          label: '市场部',
          userCount: 15,
          children: [
            { id: 6, label: '销售组', userCount: 10 },
            { id: 7, label: '推广组', userCount: 5 },
          ],
        },
        {
          id: 8,
          label: '人事部',
          userCount: 10,
        },
      ],
    },
  ];
});
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :width="dialogWidth"
    :fullscreen="isFullscreen"
    :class="fullscreenClass"
    @close="handleClose"
    destroy-on-close
  >
    <!-- 头部工具栏 -->
    <template #header>
      <div class="flex w-full items-center justify-between">
        <span class="text-lg font-semibold">{{ title }}</span>
        <div class="flex space-x-2">
          <!-- 查看已选按钮 -->
          <el-badge
            :value="selectedUsers.length"
            :max="99"
            :hidden="selectedUsers.length === 0"
          >
            <el-button
              :icon="View"
              @click="showSelectedDrawer = true"
              :disabled="selectedUsers.length === 0"
            >
              已选用户
            </el-button>
          </el-badge>

          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户或部门"
            clearable
            class="w-60"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-tooltip
            :content="isFullscreen ? '退出全屏' : '全屏'"
            placement="top"
          >
            <el-button
              :icon="isFullscreen ? FullScreenExit : FullScreen"
              circle
              @click="toggleFullscreen"
            />
          </el-tooltip>
        </div>
      </div>
    </template>

    <!-- 主要内容区域 -->
    <div class="flex h-full flex-col">
      <div class="flex min-h-0 flex-1 gap-4">
        <!-- 左侧部门树 -->
        <div class="flex w-1/3 flex-col overflow-hidden rounded-lg border">
          <div class="border-b bg-gray-50 p-3 font-medium">部门列表</div>
          <div class="flex-1 overflow-auto">
            <ElTree
              ref="treeRef"
              :data="departmentTree"
              :props="treeProps"
              node-key="id"
              :default-expand-all="false"
              :expand-on-click-node="false"
              :highlight-current="true"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              class="p-2"
            >
              <template #default="{ node, data }">
                <span class="flex items-center">
                  <el-icon class="mr-1"><OfficeBuilding /></el-icon>
                  <span>{{ node.label }}</span>
                  <span class="ml-2 text-xs text-gray-500">
                    ({{ data.userCount || 0 }})
                  </span>
                </span>
              </template>
            </ElTree>
          </div>
        </div>

        <!-- 右侧用户列表 -->
        <div class="flex flex-1 flex-col overflow-hidden rounded-lg border">
          <div
            class="flex min-h-[44px] items-center justify-between border-b bg-gray-50 p-3 font-medium"
          >
            <span>用户列表</span>
            <div
              class="flex items-center space-x-2 transition-all duration-200"
            >
              <span class="whitespace-nowrap text-sm text-gray-500">
                已选择 {{ selectedUsers.length }} 个用户
              </span>
              <el-button
                type="primary"
                text
                size="small"
                @click="clearSelection"
                class="transition-all duration-200"
                :class="[
                  selectedUsers.length > 0
                    ? 'scale-100 opacity-100'
                    : 'pointer-events-none scale-95 opacity-0',
                ]"
              >
                清空选择
              </el-button>
            </div>
          </div>

          <div class="flex-1 overflow-auto">
            <ElTable
              ref="tableRef"
              :data="userList"
              :height="tableHeight"
              @selection-change="handleSelectionChange"
              v-loading="loading"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="姓名" min-width="120">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <el-avatar :size="32" :src="row.avatar" class="mr-3">
                      {{ row.name.charAt(0) }}
                    </el-avatar>
                    <div>
                      <div class="font-medium">{{ row.name }}</div>
                      <div class="text-xs text-gray-500">
                        {{ row.position }}
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="department" label="部门" min-width="150" />
              <el-table-column prop="email" label="邮箱" min-width="180" />
              <el-table-column prop="phone" label="电话" min-width="130" />
              <el-table-column label="状态" width="80">
                <template #default="{ row }">
                  <el-tag
                    :type="row.status === 'active' ? 'success' : 'info'"
                    size="small"
                  >
                    {{ row.status === 'active' ? '在职' : '离职' }}
                  </el-tag>
                </template>
              </el-table-column>
            </ElTable>
          </div>

          <!-- 分页 -->
          <div
            class="flex items-center justify-between border-t bg-gray-50 p-3"
          >
            <div class="text-sm text-gray-500">共 {{ totalUsers }} 个用户</div>
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalUsers"
              layout="sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="mt-4 flex justify-end border-t pt-4">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="selectedUsers.length === 0"
        >
          确认选择 ({{ selectedUsers.length }})
        </el-button>
      </div>
    </div>

    <!-- 已选用户抽屉 -->
    <el-drawer
      v-model="showSelectedDrawer"
      title="已选用户"
      direction="rtl"
      size="400px"
      destroy-on-close
    >
      <div class="flex h-full flex-col">
        <!-- 已选用户统计 -->
        <div class="border-b p-4">
          <div class="flex items-center justify-between">
            <span class="text-lg font-medium">已选择用户</span>
            <el-badge :value="selectedUsers.length" type="primary" />
          </div>
          <p class="mt-1 text-sm text-gray-500">可在此查看和管理已选择的用户</p>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-between border-b bg-gray-50 p-3">
          <el-button
            type="primary"
            text
            size="small"
            :disabled="selectedUsers.length === 0"
            @click="clearSelection"
          >
            清空所有
          </el-button>
          <el-button
            type="danger"
            text
            size="small"
            :disabled="selectedDrawerUsers.length === 0"
            @click="removeSelectedFromDrawer"
          >
            移除选中
          </el-button>
        </div>

        <!-- 已选用户列表 -->
        <div class="flex-1 overflow-auto">
          <div
            v-if="selectedUsers.length === 0"
            class="py-8 text-center text-gray-400"
          >
            <el-icon size="48" class="mb-2"><User /></el-icon>
            <p>暂无已选用户</p>
          </div>

          <div v-else class="p-2">
            <div
              v-for="user in selectedUsers"
              :key="user.id"
              class="mb-2 flex items-center rounded-lg border p-3 transition-colors hover:bg-gray-50"
              :class="{
                'border-blue-200 bg-blue-50': selectedDrawerUsers.includes(
                  user.id,
                ),
              }"
            >
              <el-checkbox
                v-model="selectedDrawerUsers"
                :label="user.id"
                class="mr-3"
              />

              <el-avatar :size="40" :src="user.avatar" class="mr-3">
                {{ user.name.charAt(0) }}
              </el-avatar>

              <div class="min-w-0 flex-1">
                <div class="truncate font-medium text-gray-900">
                  {{ user.name }}
                </div>
                <div class="truncate text-sm text-gray-500">
                  {{ user.position }}
                </div>
                <div class="truncate text-xs text-gray-400">
                  {{ user.department }}
                </div>
              </div>

              <el-button
                type="danger"
                text
                size="small"
                :icon="Delete"
                @click="removeUser(user.id)"
                class="ml-2"
              />
            </div>
          </div>
        </div>

        <!-- 抽屉底部 -->
        <div class="border-t p-4">
          <el-button
            type="primary"
            class="w-full"
            @click="showSelectedDrawer = false"
          >
            完成查看
          </el-button>
        </div>
      </div>
    </el-drawer>
  </el-dialog>
</template>

<style scoped>
:deep(.fullscreen-dialog .el-dialog) {
  width: 100%;
  height: 100%;
  max-height: 100%;
  margin: 0 !important;
}

:deep(.fullscreen-dialog .el-dialog__body) {
  height: calc(100% - 120px);
  overflow: auto;
}
</style>
